package com.ego.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ego.common.constant.CouponConstant;
import com.ego.common.constant.SystemConstant;
import com.ego.common.to.SeckillRespTo;
import com.ego.common.to.order.SeckillOrderTo;
import com.ego.common.util.Result;
import com.ego.coupon.feign.ProductFeign;
import com.ego.coupon.po.SeckillSession;
import com.ego.coupon.po.SeckillSkuRelation;
import com.ego.coupon.service.SeckillService;
import com.ego.coupon.service.SeckillSessionService;
import com.ego.coupon.to.SeckillSkuInfoTo;
import com.ego.coupon.to.product.SkuInfoTo;
import com.ego.common.vo.coupon.SeckillParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @program: ego
 * @description: 秒杀服务实现
 * @author: KamTang
 * @create: 2022-12-30 16:20
 **/
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private SeckillSessionService seckillSessionService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSku() {
        // 获取需要参与秒杀的活动
        List<SeckillSession> sessions = seckillSessionService.getLastDaySession();
        if (!CollectionUtils.isEmpty(sessions)) {
            // 上架商品
            // 缓存到Redis：缓存活动信息；
            cacheSessionInfo(sessions);

            // 缓存活动的关联商品信息
            cacheSessionSkuRelation(sessions);
        }
    }

    @Override
    public List<SeckillSkuInfoTo> getCurrentSeckillSku() {
        // 确定当前时间属于哪个秒杀场次
        long time = System.currentTimeMillis();
        Set<String> keys = stringRedisTemplate.keys(CouponConstant.SESSION_CACHE_PREFIX + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            for (String key : keys) {
                String replace = key.replace(CouponConstant.SESSION_CACHE_PREFIX, "");
                String[] split = replace.split("_");
                long start = Long.parseLong(split[0]);
                long end = Long.parseLong(split[1]);
                if (time >= start && time <= end) {
                    // 获取这个秒杀场次需要的所有商品信息
                    List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                    if (!CollectionUtils.isEmpty(range)) {
                        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate
                                .boundHashOps(CouponConstant.SKU_SECKILL_CACHE_PREFIX);
                        List<String> jsons = hashOps.multiGet(range);
                        if (!CollectionUtils.isEmpty(jsons)) {
                            return jsons.stream()
                                    .map(json -> JSON.parseObject(json, SeckillSkuInfoTo.class))
                                    .collect(Collectors.toList());
                        }
                    }
                    break;
                }
            }
        }
        return null;
    }

    @Override
    public SeckillSkuInfoTo getSeckillSkuBySkuId(Long skuId) {
        // 找到所有需要参与秒杀的商品key
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(CouponConstant.SKU_SECKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (!CollectionUtils.isEmpty(keys)) {
            // 正则表达式获取skuId的商品
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String jsonStr = hashOps.get(key);
                    if (StringUtils.isNotEmpty(jsonStr)) {
                        SeckillSkuInfoTo info = JSON.parseObject(jsonStr, SeckillSkuInfoTo.class);
                        // 随机码处理
                        long now = System.currentTimeMillis();
                        if (!(now >= info.getStartTime() && now <= info.getEndTime())) {
                            info.setRandomCode(null);
                            return null;
                        } else {
                            return info;
                        }
                    }
                }
            }
        }

        return null;
    }

    @Override
    public SeckillRespTo kill(SeckillParam seckillParam) {
        // 获取当前秒杀商品的详情信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(CouponConstant.SKU_SECKILL_CACHE_PREFIX);
        String json = hashOps.get(seckillParam.getKillId());
        if (StringUtils.isNotEmpty(json)) {
            SeckillSkuInfoTo seckillSkuInfo = JSON.parseObject(json, SeckillSkuInfoTo.class);
            // 校验合法性
            Long startTime = seckillSkuInfo.getStartTime();
            Long endTime = seckillSkuInfo.getEndTime();
            long currentTime = System.currentTimeMillis();

            // 校验时间合法性
            if (currentTime >= startTime && currentTime <= endTime) {
                // 校验随机码和商品ID
                String randomCode = seckillSkuInfo.getRandomCode();
                String key = seckillSkuInfo.getPromotionSessionId() + "_" + seckillSkuInfo.getSkuId();
                if (seckillParam.getCode().equals(randomCode) && seckillParam.getKillId().equals(key)) {
                    // 验证购物数量
                    if (seckillParam.getNum() <= seckillSkuInfo.getSeckillLimit()) {
                        // 验证用户是否已经购买过。幂等性；只要秒杀成功，就去占位 userId_sessionId_skuId
                        String userSessionSkuKey = seckillParam.getMemberId() + "_" + key;
                        // 自动过期
                        long ttl = endTime - currentTime;
                        Boolean aBoolean = stringRedisTemplate.opsForValue()
                                .setIfAbsent(userSessionSkuKey, seckillParam.getNum().toString(), ttl, TimeUnit.MILLISECONDS);
                        // 如果占位成功，说明没有买过，否则就是说明买过
                        if (Boolean.TRUE.equals(aBoolean)) {
                            RSemaphore semaphore = redissonClient.getSemaphore(CouponConstant.SKU_STOCK_SEMAPHORE + randomCode);
                            boolean tryAcquire = semaphore.tryAcquire(seckillParam.getNum());
                            if (tryAcquire) {
                                // 快速秒杀
                                String orderSn = IdWorker.getTimeId().substring(0, 32);
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                SeckillRespTo respTo = new SeckillRespTo();
                                seckillOrderTo.setOrderSn(orderSn);
                                seckillOrderTo.setMemberId(seckillParam.getMemberId());
                                seckillOrderTo.setNum(seckillParam.getNum());
                                seckillOrderTo.setPromotionSessionId(seckillSkuInfo.getPromotionSessionId());
                                seckillOrderTo.setSkuId(seckillSkuInfo.getSkuId());
                                seckillOrderTo.setSeckillPrice(seckillSkuInfo.getSeckillPrice());
                                respTo.setNum(seckillParam.getNum());
                                respTo.setSkuId(seckillSkuInfo.getSkuId());
                                respTo.setOrderSn(orderSn);
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill", seckillOrderTo);
                                return respTo;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 缓存活动信息
     */
    private void cacheSessionInfo(List<SeckillSession> sessions) {
        sessions.forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String cacheKey = CouponConstant.SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean existKey = stringRedisTemplate.hasKey(cacheKey);
            if (Boolean.FALSE.equals(existKey)) {
                List<String> sessionIdAndSkuIds = session.getSkuRelations().stream()
                        .map(seckillSkuRelation -> seckillSkuRelation.getPromotionSessionId() + "_" +
                                seckillSkuRelation.getSkuId()).collect(Collectors.toList());
                log.info("sessionIdAndSkuIds => {}", sessionIdAndSkuIds);
                stringRedisTemplate.opsForList().leftPushAll(cacheKey, sessionIdAndSkuIds);
            }
        });
    }

    /**
     * 缓存活动的关联商品信息
     */
    private void cacheSessionSkuRelation(List<SeckillSession> sessions) {
        sessions.forEach(session -> {
            // 准备Hash操作
            BoundHashOperations<String, String, String> hashOps = stringRedisTemplate
                    .boundHashOps(CouponConstant.SKU_SECKILL_CACHE_PREFIX);
            session.getSkuRelations().forEach(seckillSkuRelation -> {
                // 设置随机码，保证秒杀请求不会被轻易访问，公平。
                String randomCode = UUID.randomUUID().toString().replace("-", "");
                String cacheKey = seckillSkuRelation.getPromotionSessionId() + "_" + seckillSkuRelation.getSkuId();
                // 判断缓存是否已经缓存了该数据
                if (Boolean.FALSE.equals(hashOps.hasKey(cacheKey))) {
                    // 缓存商品信息
                    SeckillSkuInfoTo seckillSkuInfoTo = new SeckillSkuInfoTo();

                    // sku基本信息
                    Result skuRes = productFeign.getSkuBySkuId(seckillSkuRelation.getSkuId());
                    if (skuRes.getCode() == SystemConstant.Status.SUCCESS.getCode()) {
                        SkuInfoTo skuInfo = skuRes.getData("skuInfo", new TypeReference<SkuInfoTo>() {
                        });
                        seckillSkuInfoTo.setSkuInfo(skuInfo);
                    }
                    // sku秒杀信息
                    buildSkuSeckillInfo(seckillSkuRelation, seckillSkuInfoTo);

                    // 设置商品的秒杀时间
                    seckillSkuInfoTo.setStartTime(session.getStartTime().getTime());
                    seckillSkuInfoTo.setEndTime(session.getEndTime().getTime());
                    seckillSkuInfoTo.setRandomCode(randomCode);

                    hashOps.put(cacheKey, JSON.toJSONString(seckillSkuInfoTo));

                    // 设置过期时间：当前系统时间到活动结束时间再额外延迟一天
                    long currentTime = System.currentTimeMillis();
                    long expireTime = (session.getEndTime().getTime() - currentTime) / 1000;
                    stringRedisTemplate.expire(cacheKey, expireTime + 24 * 60 * 60, TimeUnit.SECONDS);

                    // 使用分布式信号量作为商品的秒杀件数  限流
                    RSemaphore semaphore = redissonClient.getSemaphore(CouponConstant.SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(seckillSkuRelation.getSeckillCount());
                }
            });
        });
    }

    private void buildSkuSeckillInfo(SeckillSkuRelation seckillSkuRelation, SeckillSkuInfoTo seckillSkuInfoTo) {
        BeanUtil.copyProperties(seckillSkuRelation, seckillSkuInfoTo);
    }
}
